﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for CBatchRunner
/// </summary>
public static class CBatchRunner
{

    public static void ExecuteBatch(string s_name, string s_location, string s_wd)
    {        
        string s_batchfile_location = "\\Clients\\Alpha\\batchfiles\\" + s_name;       
        //s_working_directory = "C:\\Users\\Michael\\Documents\\Visual Studio 2010\\WebSites\\WebSite1\\Clients\\Alpha\\batchfiles";
        string s_working_directory = "C:\\TEMP\\working\\WebSite1\\Clients\\Alpha\\batchfiles";

        try
        {

            //ref:http://codebetter.com/brendantompkins/2004/05/13/run-a-bat-file-from-asp-net/
            // Get the full file path
            string strFilePath = HttpContext.Current.Server.MapPath(".") + s_batchfile_location;

            // Create the ProcessInfo object
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardError = true;
            psi.WorkingDirectory = s_working_directory;// "c:\\temp\\";

            // Start the process
            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
            // Open the batch file for reading
            System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);
            // Attach the output for reading
            System.IO.StreamReader sOut = proc.StandardOutput;
            // Attach the in for writing
            System.IO.StreamWriter sIn = proc.StandardInput;


            // Write each line of the batch file to standard input
            while (strm.Peek() != -1)
            {
                sIn.WriteLine(strm.ReadLine());
            }

            strm.Close();

            // Exit CMD.EXE
            string stEchoFmt = "# {0} run successfully. Exiting";

            sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
            sIn.WriteLine("EXIT");

            // Close the process
            proc.Close();
            // Read the sOut to a string.
            string results = sOut.ReadToEnd().Trim();
            // Close the io Streams;
            sIn.Close();
            sOut.Close();

            // Write out the results.
            //string fmtStdOut = "<font face=courier size=0>{0}</font>";
            //this.Response.Write(String.Format(fmtStdOut, results.Replace(System.Environment.NewLine, "<br>")));

        }
        catch (Exception exc)
        {
            throw exc;
        }
    }
}